package com.bbva.itradecomex.controller.parametria;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.bbva.itradecomex.bo.iface.ParametriaBO;
import com.bbva.itradecomex.domain.MultiTabla;
import com.bbva.itradecomex.util.Constantes;
import com.bbva.itradecomex.util.ITradexUtil;
import com.bbva.itradecomex.util.MessageProvider;

@Controller
@RequestScoped
@ManagedBean
public class ParamMultiTablaController {

	private static final Logger log = Logger.getLogger(ParamMultiTablaController.class);
	
	@Autowired
	private ParametriaBO parametriaBO;
	
	private MultiTabla descMultiTablaSeleccionado;
	private List<SelectItem> listDescMultiTabla;
	
	private List<MultiTabla> listDataMultiTabla;
	
	private MultiTabla rowMultiTabla;
	private boolean showNewButton;
	
	public void onPageLoad(ComponentSystemEvent event) {
		try {
			if (!FacesContext.getCurrentInstance().isPostback()) {
				cargarListDescMultiTabla();
				rowMultiTabla = new MultiTabla();
				listDataMultiTabla = new ArrayList<MultiTabla>();
				showNewButton = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					MessageProvider.getInstance().getValue("MSG_ERROR_TITLE_GENERAL"), Constantes.VACIO));
		}
	}
	
	private void cargarListDescMultiTabla() throws Exception{
		listDescMultiTabla = getListSelectItemDescMultiTabla();
	}
	
	private List<SelectItem> getListSelectItemDescMultiTabla() throws Exception{
		List<SelectItem> listSelectItem = new ArrayList<SelectItem>();
		List<MultiTabla> list = parametriaBO.paramObtenerDescMultitabla();

		if(list != null && list.size() > 0){
			for (MultiTabla multiTabla : list) {
				listSelectItem.add(new SelectItem(multiTabla, multiTabla.getDescripcion()));
			}
		}

		return listSelectItem;
	}
	
	public void cargarListDataMultiTabla(){
		String idTabla = "";
		try {
			if(descMultiTablaSeleccionado != null && 
					descMultiTablaSeleccionado.getIdTabla() != null){
				idTabla = descMultiTablaSeleccionado.getIdTabla();
				listDataMultiTabla = parametriaBO.paramObtenerDataMultitabla(idTabla);
				
				if(Constantes.CONSTANTE_SI_VAL.equals(descMultiTablaSeleccionado.getIndAgregar())){
					showNewButton = true;
				}else{
					showNewButton = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					MessageProvider.getInstance().getValue("MSG_ERROR_TITLE_GENERAL"), Constantes.VACIO));
		}
	}
	
	public void newRowMultiTabla(){
		try {			
			Map<String, Object> map = parametriaBO.paramOperationMultitabla(Constantes.OPERACION_INSERTAR, rowMultiTabla);
			BigDecimal outRetorno = (BigDecimal)map.get("out_retorno");
			ITradexUtil.messageStoredProcedureCRUD(outRetorno, map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					MessageProvider.getInstance().getValue("MSG_ERROR_TITLE_GENERAL"), Constantes.VACIO));
		}
		cargarListDataMultiTabla();
	}
	
	public void onEdit(RowEditEvent event) {
		try {
			Map<String, Object> map = parametriaBO.paramOperationMultitabla(Constantes.OPERACION_ACTUALIZAR, 
					((MultiTabla) event.getObject()));
			BigDecimal outRetorno = (BigDecimal)map.get("out_retorno");
			ITradexUtil.messageStoredProcedureCRUD(outRetorno, map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					MessageProvider.getInstance().getValue("MSG_ERROR_TITLE_GENERAL"), Constantes.VACIO));
		}
		cargarListDataMultiTabla();
    }
	
	public void deleteRowMultiTabla(){
		try {
			Map<String, Object> map = parametriaBO.paramOperationMultitabla(Constantes.OPERACION_ELIMINAR, rowMultiTabla);
			BigDecimal outRetorno = (BigDecimal)map.get("out_retorno");
			ITradexUtil.messageStoredProcedureCRUD(outRetorno, map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
					MessageProvider.getInstance().getValue("MSG_ERROR_TITLE_GENERAL"), Constantes.VACIO));
		}
		cargarListDataMultiTabla();
	}
	
	public void initVarFormSave(){
		rowMultiTabla = new MultiTabla();
		
		MultiTabla multi = listDataMultiTabla.get(listDataMultiTabla.size() - 1);
		
		rowMultiTabla.setIdTabla(multi.getIdTabla());
		String newIdItem = getNewIdItem(multi.getIdItem());
		rowMultiTabla.setIdItem(newIdItem);
		rowMultiTabla.setIdCodigo(multi.getIdTabla() + newIdItem);
	}
	
	public void initVarFormDelete(String idCodigo){
		rowMultiTabla = new MultiTabla();
		rowMultiTabla.setIdCodigo(idCodigo);
	}
	
	private String getNewIdItem(String idItem){
		int i = 0;
		while(i < idItem.length()){
			char dig = idItem.charAt(i);
			if(dig == '1' || dig == '2' || dig == '3' || dig == '4' || 
					dig == '5' || dig == '6' || dig == '7' || dig == '8' || dig == '9'){
				break;
			}
			i++;
		}
		
		int id = 0;
		try{
			id = Integer.parseInt(idItem.substring(i, idItem.length())) + 1;
		}catch(NumberFormatException e){
			log.error(e.getMessage(), e);
		}
		
		String idString = String.valueOf(id);
		
		if(idString.length() == 1){
			idString = "00" + idString;
		}else if(idString.length() == 2){
			idString = "0" + idString;
		}
		
		return idString;
	}

	public MultiTabla getDescMultiTablaSeleccionado() {
		return descMultiTablaSeleccionado;
	}

	public void setDescMultiTablaSeleccionado(MultiTabla descMultiTablaSeleccionado) {
		this.descMultiTablaSeleccionado = descMultiTablaSeleccionado;
	}

	public List<SelectItem> getListDescMultiTabla() {
		return listDescMultiTabla;
	}

	public void setListDescMultiTabla(List<SelectItem> listDescMultiTabla) {
		this.listDescMultiTabla = listDescMultiTabla;
	}

	public List<MultiTabla> getListDataMultiTabla() {
		return listDataMultiTabla;
	}

	public void setListDataMultiTabla(List<MultiTabla> listDataMultiTabla) {
		this.listDataMultiTabla = listDataMultiTabla;
	}

	public MultiTabla getRowMultiTabla() {
		return rowMultiTabla;
	}

	public void setRowMultiTabla(MultiTabla rowMultiTabla) {
		this.rowMultiTabla = rowMultiTabla;
	}

	public boolean isShowNewButton() {
		return showNewButton;
	}

	public void setShowNewButton(boolean showNewButton) {
		this.showNewButton = showNewButton;
	}
}
